package com.example.springcmw.rabbitmq.publisher;

import com.example.springcmw.rabbitmq.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 生产者接口
 */
@Service
public class PublishService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public String sendMsg(String msg) throws Exception {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("msgId", UUID.randomUUID().toString().replace("-", "").substring(0, 32));
            map.put("sendTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            map.put("msg", msg);
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_DIRECT_EXCHANGE, RabbitMQConfig.RABBITMQ_DEMO_DIRECT_ROUTING, map);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}
